<?php

namespace app\gather\controller;

use think\Controller;
use think\Request;

use app\admin\model\GPSCategory;
use app\admin\model\GPSCategoryItem;
use app\admin\model\GPSMigration;

class IndexController extends Controller
{
    /**
     * 显示资源列表
     *
     * @return \think\Response
     */
    public function index()
    {
        return $this->fetch();
    }

    /**
     * 获取分类列表 
     * Author Raven
     * Date 2018-10-08
     */
    public function getCategoryList(Request $request)
    {
        $GPSCategory = new GPSCategory();

        $categoryList = $GPSCategory->getActiveCategoryList();

        if(count($categoryList) < 1){
            $this->error("暂无可用分类");
        }

        $this->success('success', '', $categoryList);
    }

    /**
     * 获取分类字段 
     * Author Raven
     * Date 2018-10-08
     */
    public function getItemList(Request $request)
    {
        $category_id = intval($request->get('category_id'));

        if(empty($category_id)){
            $this->error("缺少必要的参数");
        }

        $GPSCategoryItem = new GPSCategoryItem();

        $itemList = $GPSCategoryItem->getActiveItemHexByCatId($category_id);

        if(count($itemList) < 1){
            $ths->error('该分类下没有字段');
        }

        $this->success('success', '', $itemList);
    }

    /**
     * 添加采集项 
     * Author Raven
     * Date 2018-10-11
     */
    public function addItemInfo(Request $request)
    {
        $category_id = intval($request->post('category_id'));
        $data = $request->post();


        if(empty($category_id)){
            $this->error("缺少必要的参数");
        }

        if(empty($data['data_lng']) || empty($data['data_lat'])){
            $this->error("坐标信息错误");
        }

        $categoryInfo = GPSCategory::where('id', $category_id)
            ->field(['hex_name'])
            ->find();

        if(empty($categoryInfo)){
            $this->error("分类信息查询失败");
        }

        $GPSCategory = new GPSCategory();
        $GPSCategoryItem = new GPSCategoryItem();
        $GPSMigration = new GPSMigration();

        $item = $GPSCategoryItem->getItemHexByCatId($category_id);

        if(count($item) < 1){
            $this->error('该分类下没有添加字段');
        }

        $table_name = $categoryInfo->hex_name;

        $res = $GPSMigration->addItemInfo($table_name, $item, $data);

        if($res == false){
            $this->error('数据添加失败');
        }

        $this->success('success');

        var_dump($categoryInfo, $item);exit;
    }
}
